package com.mgq.juc.design.alternate;

import java.util.concurrent.locks.LockSupport;

import static java.lang.Thread.sleep;

/**
 * @author MaGuangQi
 * 使用park和unpark来解决
 * @date 2021-12-17 14:40
 **/
public class TestParkUnPark {
    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) throws InterruptedException {
        ParkUnPark parkUnPark = new ParkUnPark(5);
        t1 = new Thread(() -> {
            parkUnPark.print("a", t2);
        });
        t2 = new Thread(() -> {
            parkUnPark.print("b", t3);
        });
        t3 = new Thread(() -> {
            parkUnPark.print("c", t1);
        });

        t1.start();
        t2.start();
        t3.start();


        sleep(1000);
        // 主线程去唤醒t1线程
        LockSupport.unpark(t1);
    }


}

class ParkUnPark {
    private int loopNumber;

    public ParkUnPark(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    /**
     * 打印方法
     *
     * @param str  需要打印的字符
     * @param next 需要unPark的下一个线程
     */
    public void print(String str, Thread next) {
        for (int i = 0; i < loopNumber; i++) {
            //首先让所有的线程都暂停住
            LockSupport.park();
            System.out.print(str);
            LockSupport.unpark(next);
        }
    }
}
